// /nurse_hospital/nurseHospital/rootList

import { defineStore } from 'pinia';
import { request } from '@/service/request';
import { localStg, calculateDistance } from '@/utils';
import Taro from '@tarojs/taro';

type IHospital = {
    address: string,
    area: string,
    billCode: string,
    code: string,
    createBy: string,
    createTime: string,
    hasChild: string,
    id: string,
    latitude: string,
    level: string,
    licenseName: string,
    logo: string,
    longitude: string,
    name: string,
    operatorid: string,
    operatorname: string,
    operatortel: string,
    pid: string,
    proxyorganizationname: string,
    proxyorganizationopenid: string,
    status: string,
    sysOrgCode: string,
}

interface HospitalState {
    hospitals: IHospital[],
    defaultHospital: IHospital,
    myLocation: {
        latitude: number,
        longitude: number
    },
    myAddress: string,
    distance: number | string,
}

export const useHospitalStore = defineStore('hospital-store', {
    state: (): HospitalState => ({
        hospitals: [],
        defaultHospital: {} as IHospital,
        myLocation: {
            latitude: 0,
            longitude: 0
        },
        myAddress: '',
        distance: 0,
    }),
    getters: {
        getHospitals: state => state.hospitals,
    },
    actions: {
        setHospitals(hospitals: []) {
            this.hospitals = hospitals
        },
        async setDefaultHospital(defaultHospital: IHospital) {
            this.defaultHospital = defaultHospital
            localStg.set('sys_org_code', this.defaultHospital.sysOrgCode)
            Taro.setStorageSync('defaultHospital', JSON.stringify(this.defaultHospital));
            await this.getCurrentLocation();
            this.distance = this.calculateDistanceToHospital(defaultHospital);
        },
        setDefaultHospitalById(id:string){
            if(this.hospitals.length == 0){
                setTimeout(() => {
                    this.defaultHospital = this.hospitals.find(item => item.id == id) || {} as IHospital;
                   
                    this.setDefaultHospital(this.defaultHospital);
                }, 900);
                return;
            }
            this.defaultHospital = this.hospitals.find(item => item.id == id) || {} as IHospital;
            
            this.setDefaultHospital(this.defaultHospital);
        },
        async initData() {
            const res: any = await request.get('/nurse_hospital/nurseHospital/rootList', {
                pageSize: 600
            }, {
                useErrMsg: true
            })
            if (res.success.records) {
                this.hospitals = res.success.records
                this.defaultHospital = res.success.records[0]
                this.setDefaultHospital(this.defaultHospital);
            }
        },
        // 腾讯地图API密钥
        getTencentMapKey() {
            return "5UQBZ-3CUKW-WRURZ-3I4LN-7N6WK-ZGF75";
        },
        // 将经纬度转换为地址
        reverseGeocode(latitude: number, longitude: number): Promise<string> {
            return new Promise<string>((resolve, reject) => {
                Taro.request({
                    url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${this.getTencentMapKey()}`,
                    success: (res: any) => {
                        if (res.data.status === 0) {
                            const address = res.data.result.address;
                            const formattedAddress = res.data.result.formatted_addresses?.recommend || address;
                            resolve(formattedAddress);
                        } else {
                            reject(new Error('获取地址失败'));
                        }
                    },
                    fail: (error: any) => {
                        reject(error);
                    }
                });
            });
        },
        // 获取当前位置
        async getCurrentLocation(): Promise<void> {
            if(this.myLocation.latitude != 0 && this.myLocation.longitude != 0){
                return;
            }
            return new Promise((resolve, reject) => {
                Taro.getLocation({
                    type: 'wgs84',
                    needFullAccuracy: true,
                    success: async (res) => {
                        this.myLocation.latitude = res.latitude;
                        this.myLocation.longitude = res.longitude;
                        
                        try {
                            // 将经纬度转换为地址
                            const address = await this.reverseGeocode(res.latitude, res.longitude);
                            this.myAddress = address;
                            resolve();
                        } catch (error) {
                            this.myAddress = '地址获取失败';
                            resolve(); // 即使地址获取失败，位置获取成功也算成功
                        }
                    },
                    fail: (error) => {
                        reject(error);
                    }
                });
            });
        },
        // 计算到指定医院的距离
        calculateDistanceToHospital(hospital: IHospital): number | string {
            if (!hospital.latitude || !hospital.longitude) {
                return 0;
            }
            return calculateDistance(
                this.myLocation.latitude, 
                this.myLocation.longitude, 
                parseFloat(hospital.latitude), 
                parseFloat(hospital.longitude), 
                2
            );
        },
       
    }
});
